<template>
  <div class="avatar-container" :class="{ top: imgUrl != '' }" :style="backgroundStyle" @click="open">
    <!-- 图片裁剪上传组件 -->
    <div class="model">
      <el-button icon='ArrowUp' link style="color: white; font-size: 16px;">提交签章</el-button>
    </div>
    <el-dialog :title="title" :model-value="dialogVisibleCorpper" width="800px" append-to-body @opened="openDialog"
      :before-close="beforeClose">
      <el-row>
        <el-col :span="24" style="height: 300px">
          <vue-cropper ref="cropper" :img="options.img" :info="true" :autoCrop="options.autoCrop"
            :autoCropWidth="options.autoCropWidth" :autoCropHeight="options.autoCropHeight" :fixedBox="options.fixedBox"
            :outputType="options.outputType" :outputSize="options.outputSize" :fixed="options.fixed"
            :fixedNumber="options.fixedNumber" @realTime="realTime" v-if="showCropper" />
        </el-col>
      </el-row>
      <el-row style="margin-top: 12px">
        <el-col :span="12">
          <el-row>
            <el-col :span="8">
              <el-upload action="#" :http-request="() => { }" :before-upload="beforeUpload" :show-file-list="false">
                <el-button>选择文件</el-button>
              </el-upload>
            </el-col>
            <el-col :span="4">
              <el-button :icon="Plus" @click="changeScale(1)"></el-button>
            </el-col>
            <el-col :span="4">
              <el-button :icon="Minus" @click="changeScale(-1)"></el-button>
            </el-col>
            <el-col :span="4">
              <el-button :icon="RefreshLeft" @click="rotateLeft()"></el-button>
            </el-col>
            <el-col :span="4">
              <el-button :icon="RefreshRight" @click="rotateRight()"></el-button>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="4" :offset="8" style="margin-left: 22.3%">
          <el-button type="primary" @click="determine()">上 传</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  Plus,
  Minus,
  RefreshLeft,
  RefreshRight,
} from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import "vue-cropper/dist/index.css";
import { VueCropper } from "vue-cropper";
import { getCurrentInstance, ref, reactive, watch, computed } from "vue";
import request from '/@/utils/request';
import { userStore } from '/@/stores/userMolde';
import { useUserInfo } from '/@/stores/userInfo';
const userStores = userStore();
//引入beasurl
const url = import.meta.env.VITE_API_URL
const { proxy } = getCurrentInstance();
const props = defineProps({
  dialogVisibleCorpper: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    default: "上传图片",
  }
});
const showCropper = ref(false);
const options = ref({
  img: 'blob', // 裁剪图片的地址
  autoCropWidth: 400, // 默认生成截图框宽度 默认容器的 80%
  autoCropHeight: 200, // 默认生成截图框高度 默认容器的 80%
  outputType: "png", // 裁剪生成图片的格式 jpeg, png, webp
  autoCrop: true, // 是否默认生成截图框
  fixedBox: true, // 固定截图框大小
  outputSize: 0.5, // 裁剪生成图片的质量
  fixed: true,
  fixedNumber: [3, 2]
});
const previews = ref({
  url: "",
});
//图片地址
const imgUrl = ref('')
const open = () => {
  emit("update:dialogVisibleCorpper", true);
}
// 打开裁剪弹窗
const openDialog = () => {
  showCropper.value = true;
};
// 修改图片大小 正数为变大 负数变小
const changeScale = (num) => {
  num = num || 1;
  proxy.$refs.cropper.changeScale(num);
};
// 向左边旋转90度
const rotateLeft = () => {
  proxy.$refs.cropper.rotateLeft();
};
// 向右边旋转90度
const rotateRight = () => {
  proxy.$refs.cropper.rotateRight();
};
// 上传图片处理
const beforeUpload = (rawFile) => {
  if (rawFile.type.indexOf("image/") == -1) {
    ElMessage.error("请上传图片类型文件!");
    return false;
  }
  if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error("文件大小不能超过10MB!");
    return false;
  }
  const reader = new FileReader();
  reader.readAsDataURL(rawFile);
  reader.onload = () => {
    // 图片在这里
    options.value.img = reader.result;
  };
};
// 实时预览事件
const realTime = (data) => {
  previews.value = data;
};
const emit = defineEmits(["update:dialogVisibleCorpper", "confirm"]);
// 计算属性，返回背景图片样式
const backgroundStyle = computed(() => {
  return userStores.imgUrl != ''
    ? `background-image: url(${imgFn(userStores.imgUrl)}); background-size: cover; background-position: center;`
    : ''
});
// 关闭弹窗
const beforeClose = () => {
  options.value.img = null;
  previews.value.url = "";
  emit("update:dialogVisibleCorpper", false);
};
const imgFn = (img: void) => {
  return url + img
}
// 提交图片
const determine = () => {
  //开始截图
  proxy.$refs.cropper.startCrop()
  proxy.$refs.cropper.getCropBlob(async data => {
    const file = new File([data], 'image.png', { type: 'image/png' });
    // 现在 file 变量中存储了一个 File 对象
    console.log(file);
    let formData = new FormData();
    formData.append('file', file);

    try {
      const { data } = await request({
        url: '/admin/sys-file/upload',
        method: 'post',
        headers: {
          'Content-Type': 'multipart/form-data',
        },
        data: formData,
      });
      imgUrl.value = data.url
      userStores.setImgUrl(data.url)
      console.log(imgUrl.value);
      emit("confirm");
    } catch (error) {
    }
  })
};
// const downloadFile = (file) => {
//   // 创建一个 URL 对象
//   const url = URL.createObjectURL(file);

//   // 创建一个隐藏的下载链接
//   const link = document.createElement('a');
//   link.href = url;
//   link.download = file.name || 'downloaded-file'; // 设置下载的文件名

//   // 触发下载
//   link.click();

//   // 释放 URL 对象，避免内存泄漏
//   URL.revokeObjectURL(url);
// }
defineExpose({
  imgUrl,
  imgFn,
});
</script>

<style scoped>
.avatar-container {
  width: 100%;
  height: 100%;
  cursor: pointer;
  border: 1px dashed #d9d9d9;
  position: relative;

  .model {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    opacity: 0;
    background-color: #000000;
    transition: opacity .2s ease;
    /* 添加一秒的动画效果 */
    position: absolute;
    top: 0;
    left: 0;
  }

  /* 鼠标悬停时显示遮罩层 */
  &:hover .model {
    opacity: 0.5;
    /* 鼠标悬停时设置遮罩层透明度 */
  }
}

.top {
  /* bgc */
}

.img-box {
  border-radius: 50%;
  border: 1px solid #ccc;
  width: 10vw;
  height: 10vw;
}

.preview-box {
  position: absolute;
  top: 50%;
  transform: translate(50%, -50%);
  width: 200px;
  height: 200px;
  border-radius: 50%;
  border: 1px solid #ccc;
  overflow: hidden;
}
</style>